//目前不完善，后续会补充，整体结构没问题
import axios from 'axios'
import { useGlobalStore } from '@/store'
import { Toast } from 'vant'
const globalStore = useGlobalStore()
const baseURL = 'http://yapi.52react.cn/mock/6'
const requestTimeout = 10000
const instance = axios.create({
  baseURL,
  timeout: requestTimeout,
  headers: {
    'Content-Type': 'application/json;charset=UTF-8'
  }
})
// 请求拦截器
instance.interceptors.request.use(
  config => {
    console.log('%c 🍛 请求链接: ', 'font-size:20px;background-color: #33A5FF;color:#fff;', config.url)
    //新增 stroe loading显示
    globalStore.setLoading(true)
    return config
  },
  error => {
    //异步错误提示
    globalStore.setLoading(false)
    return Promise.reject(error)
  }
)
// 响应拦截  异常处理
instance.interceptors.response.use(
  response => {
    //新增 stroe loading隐藏
    globalStore.setLoading(false)
    const { success, msg } = response.data
    console.log('%c 🍚 success: ', 'font-size:20px;background-color: #EA7E5C;color:#fff;', response.data)
    // 操作成功
    if (success) {
      return response.data
    } else {
      msg && Toast.fail(msg)
      return Promise.reject()
    }
  },
  error => {
    //新增 stroe loading隐藏
    globalStore.setLoading(false)
    const { response } = error
    if (response && response.data) {
      return Promise.reject(error)
    } else {
      const { message } = error
      console.log(message)
      return Promise.reject(error)
    }
  }
)

export default instance
